package cdu.hjx.project.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class DeterministicAesEncryption {
    public static void main(String[] args) {
        String secretKey = "VpV2UosNCVe9pfzo"; // 16字节密钥
        String plainText = "123456";
        String fixedIV = "0123456789abcdef"; // 16字节的固定IV，用于测试

        try {
            String encryptedData = encryptAESWithFixedIV(plainText, secretKey, fixedIV);
            System.out.println("固定IV的加密结果: " + encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String encryptAESWithFixedIV(String plainText, String secretKey, String fixedIV) throws Exception {
        // 将固定IV字符串转为字节数组
        byte[] ivBytes = fixedIV.getBytes(StandardCharsets.UTF_8);
        // 将密钥字符串转为字节数组
        byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
        SecretKey key = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivBytes));

        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

        // 组合IV和密文: IV(16字节) + 密文
        byte[] combined = new byte[ivBytes.length + encryptedBytes.length];
        System.arraycopy(ivBytes, 0, combined, 0, ivBytes.length);
        System.arraycopy(encryptedBytes, 0, combined, ivBytes.length, encryptedBytes.length);

        return Base64.getEncoder().encodeToString(combined);
    }
}
